package org.shan.sevice;

import org.shan.security.core.rbac.RbacService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by amanda.shan on 2019/3/19.
 */
@Service("rbacService")
public class RbacServiceImpl implements RbacService, InitializingBean {

    private Logger logger = LoggerFactory.getLogger(RbacServiceImpl.class);

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    private Set<String> urlRoles;

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();

        boolean hasPermission = false;
        // 有可能 principal 是一个Anonymous
        // 所以只要是一个UserDetails那么就能标识是经过了我们自己的数据库查询的
        // 当前需要先配置UserDetailsServices
        if (principal instanceof UserDetails) {

            UserDetails details = (UserDetails) principal;
            Collection<? extends GrantedAuthority> grantedAuthorities = details.getAuthorities();
            String username = details.getUsername();

            logger.info(username + "拥有的权限" + grantedAuthorities);

            //读取用户所拥有权限的所有URL
            for (String url : urlRoles) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }

        }

        return hasPermission;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        urlRoles = new HashSet<>();

        urlRoles.add("/pre/data");
    }
}
